package rest

import (
	"github.com/labstack/echo/v4"

	"bmember/internal/service"
)

type schHandler struct {
	*Base
	name string
}

// NewScheduleHandler 定时任务
func NewScheduleHandler() *schHandler {
	return &schHandler{
		Base: base,
		name: "card_handler",
	}
}

// Register 注册路由
func (hl *schHandler) Register(r *echo.Group) {
	// 充值订单重试
	r.GET("/v1/recharge-order/pay", hl.rechargePayCheck)
	// 创建定时任务，for test
	r.POST("/v1/create", hl.createSchedule)
	// 重试消息消费
	r.POST("/v1/msg/redo", hl.redoMessage)
}

func (hl *schHandler) rechargePayCheck(c echo.Context) error {
	ctx := c.Request().Context()
	limit, errL := parseInt64Query(c, "limit")
	if errL != nil {
		return errL
	}
	errL = service.GetScheduleSrv().RechargeOrderPayCheck(ctx, int(limit))
	return hl.SimpleRet(c, nil, errL)
}

func (hl *schHandler) createSchedule(c echo.Context) error {
	ctx := c.Request().Context()
	type param struct {
		SchType int8   `json:"sch_type"`
		Param   string `json:"param"`
	}
	req := &param{}
	if errL := hl.ParseBody(c, req); errL != nil {
		return errL
	}
	ret, errL := service.GetScheduleSrv().CreateSchedule(ctx, req.SchType, []byte(req.Param))
	return hl.SimpleRet(c, ret, errL)
}

func (hl *schHandler) redoMessage(c echo.Context) error {
	ctx := c.Request().Context()
	type param struct {
		MsgIds []int64 `json:"msg_ids" validate:"required"`
	}
	req := &param{}
	if errL := hl.ParseBody(c, req); errL != nil {
		return errL
	}
	errL := service.GetScheduleSrv().RedoMessages(ctx, req.MsgIds)
	return hl.SimpleRet(c, nil, errL)
}
